/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.controller;

import br.com.jr2tecnologia.LoggerFactory;
import br.com.jr2tecnologia.SMSUtil;
import br.com.jr2tecnologia.mail.Mailbox;
import br.com.jr2tecnologia.model.BankAccountPersistenceLocal;
import br.com.jr2tecnologia.model.CompanyPersistenceLocal;
import br.com.jr2tecnologia.model.LoginPersistenceLocal;
import br.com.jr2tecnologia.model.RolePersistenceLocal;
import br.com.jr2tecnologia.model.entity.BankAccount;
import br.com.jr2tecnologia.model.entity.Company;
import br.com.jr2tecnologia.model.entity.Login;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.ejb.EJB;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author ronildo
 */
@ManagedBean
@SessionScoped
public class RegisterMBean implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger();

    private String companyName;
    private String userName;
    private String userMail;
    private String userPassword;
    private String confirmUserPassword;
    private String confirmUserMail;

    @EJB
    private CompanyPersistenceLocal companyPersistenceFacade;
    @EJB
    private LoginPersistenceLocal loginPersistenceFacade;
    @EJB
    private BankAccountPersistenceLocal bankAccountPersistence;
    @EJB
    private RolePersistenceLocal rolePersistence;

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getUserMail() {
        return userMail;
    }

    public void setUserMail(String userMail) {
        this.userMail = userMail;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getConfirmUserPassword() {
        return confirmUserPassword;
    }

    public void setConfirmUserPassword(String confirmUserPassword) {
        this.confirmUserPassword = confirmUserPassword;
    }

    public String getConfirmUserMail() {
        return confirmUserMail;
    }

    public void setConfirmUserMail(String confirmUserMail) {
        this.confirmUserMail = confirmUserMail;
    }

    public void register(){
        logger.info("register new login");
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage message = null;
        Login login = loginPersistenceFacade.findLoginByEmail(userMail);
        Company company = companyPersistenceFacade.findByName(companyName);

        if(companyName == null || companyName.equals("") ||
            userName == null || userName.equals("") ||
            userMail == null || userMail.equals("") ||
            userPassword == null || userPassword.equals("") ||
            confirmUserPassword == null || confirmUserPassword.equals("") ||
            confirmUserMail == null || confirmUserMail.equals("")){
            logger.warning("missing fields for register new user");
            message = new FacesMessage("Preencha todos os campos antes de prosseguir");
            context.addMessage(null, message);
        }else if(login != null){
            logger.warning("this email '"+userMail+"' is already registered");
            message = new FacesMessage("Este e-mail ja esta cadastrado, favor tente outro.");
            context.addMessage(null, message);
        }else if(company != null){
            logger.warning("this email '"+companyName+"' is already registered");
            message = new FacesMessage("Esta empresa ja está cadastrado, favor tente outra.");
            context.addMessage(null, message);
        }else if(!userMail.equals(confirmUserMail)){
            message = new FacesMessage("Sua confirmação de e-mail esta errada");
            context.addMessage(null, message);
        }else if(!userPassword.equals(confirmUserPassword)){
            message = new FacesMessage("Sua confirmação de senha esta errada");
            context.addMessage(null, message);
        }else{
            String activationKey = SMSUtil.makeActivationKey();
            company = new Company();
            company.setName(companyName);
            company.setValueSendSms(0.15d);
            companyPersistenceFacade.persist(company);
            company = companyPersistenceFacade.findByName(companyName);

            long qtdSmsBuyed = Math.round(1.2 / company.getValueSendSms());
            BankAccount bankAccount = new BankAccount();
            bankAccount.setName("Sua Conta");
            bankAccount.setCompany(company);
            bankAccount.setDefaultBankAccount(true);
            bankAccount.setBalance(0.0);
            bankAccount.setQuantitySmsBuyed(qtdSmsBuyed);
            bankAccountPersistence.persist(bankAccount);
            //bankAccount = bankAccountPersistence.findByCompany(company);


            login = new Login();
            login.setName(userName);
            login.setPassword(userPassword);
            login.setEmail(userMail);
            login.setDescription("user registered by site");
            login.setBlocked(true);
            login.setActivationKey(activationKey);
            login.setCompany(company);
            login.setBankAccount(bankAccount);
            login.setRole(rolePersistence.findByName("Administrator"));
            loginPersistenceFacade.persist(login);

            boolean sendered = Mailbox.postNewUser(userMail, activationKey);
            if(sendered)
                context.addMessage(null, new FacesMessage("Seu registro foi enviado por e-mail"));
            else
                context.addMessage(null, new FacesMessage("Tivemos um problema ao registrar seu pedido, por favor tente novamente."));
        }
    }
}
